package br.ucb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.ucb.connection.MyConnection;
import br.ucb.enumCategoriaItem.EnumCategoriaItem;
import br.ucb.model.Item;

public class ItemDao {
	public void add(Item item) {
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "INSERT INTO ITEM VALUES(0,?,?,?);";
			st = con.prepareStatement(sql);
			st.setString(1, item.getNome());
			st.setFloat(2, item.getPreco());
			st.setInt(3, item.getCategoria().getId());
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public List<Item> findAll() {
		Connection con;
		Statement st;
		ResultSet rs;
		String sql;
		List<Item> itens = new ArrayList<Item>();

		try {
			con = MyConnection.getConnection();
			st = con.createStatement();
			sql = "SELECT * FROM ITEM;";
			rs = st.executeQuery(sql);
			while (rs.next()) {
				itens.add(new Item(rs.getInt("ID"), rs.getString("DESCRICAO"),
						rs.getFloat("PRECO"), EnumCategoriaItem.findEnumById(rs
								.getInt("CATEGORIA"))));
			}
			MyConnection.closeConnection(con, st, rs);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return itens;
	}

	public void update(Item item) {
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "UPDATE ITEM SET DESCRICAO=?,PRECO=? where ID=?;";
			st = con.prepareStatement(sql);
			st.setString(1, item.getNome());
			st.setFloat(2, item.getPreco());
			st.setInt(3, item.getId());
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void delete(Item item) {
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "DELETE FROM ITEM WHERE ID=?;";
			st = con.prepareStatement(sql);
			st.setInt(1, item.getId());
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
